package com.qwz.example;

import com.qwz.common.DbClose;

import java.sql.*;
/**  
* @Description: 代理对象，代理用户的数据对象
* @Package com.qwz.example.Proxy
* @author Qiuwuzhi
* @date 2019/12/23 11:05
* @version V1.0
*/
public class Proxy implements UserModelApi {

    private UserModel realSubject;

    public Proxy(UserModel realSubject) {
        this.realSubject = realSubject;
    }


    public String getUserId() {
        return realSubject.getUserId();
    }

    public void setUserId(String userId) {
        realSubject.setUserId(userId);
    }

    public String getName() {
        return realSubject.getName();
    }

    public void setName(String name) {
        realSubject.setName(name);
    }

    public void setSex(String sex) {
        realSubject.setSex(sex);
    }

    public void setDepId(String depId) {
        realSubject.setDepId(depId);
    }

    /**
     * 标示是否已经重新装载过数据了
     */
    private boolean loaded = false;

    public String getSex() {
        if (!this.loaded) {
            reload();
            this.loaded = true;
        }
        return realSubject.getSex();
    }

    public String getDepId() {
        //需要判断是否已经装载过了
        if (!this.loaded) {
            //从数据库中重新装载
            reload();
            //设置重新装载的标志位true
            this.loaded = true;
        }
        return realSubject.getDepId();
    }

    private void reload() {
        System.out.println("重新查询数据库，获取完整的用户信息，userId" + realSubject.getUserId());
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet resultSet = null;
        //操作数据库示例代码
        try {
            conn = DriverManager.getConnection("");
            String sql = "select * from t_user where userid=?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, realSubject.getUserId());
            resultSet = ps.executeQuery();
            if (resultSet.next()) {
                //只需要重新获取除了userId和name以外的信息
                realSubject.setSex(resultSet.getString("sex"));
                realSubject.setDepId(resultSet.getString("depid"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DbClose.close(conn, ps, resultSet);
        }
    }

}
